import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Scanner;

// UDP版本的回显客户端
public class UdpEchoClient {

    private DatagramSocket socket = null;
    private String serverIp = null;
    private int serverPort = 0;

    // 一次通信，需要两个ip和两个端口
    // 客户端的IP为127.0.0.1 客户端的端口号是系统随机分配的，可通过netstat -ano查询
    // 服务器IP和端口号需要告诉客户端，才能顺利将信息发给服务器
    public UdpEchoClient(String serverIp,int serverPort) throws SocketException {
        socket = new DatagramSocket();
        this.serverIp = serverIp;
        this.serverPort = serverPort;
    }

    public void start() throws IOException {
        System.out.println("客户端启动！");
        Scanner scanner = new Scanner(System.in);
        while(true){
            System.out.print("> ");
            // 1，从控制台读取要发送的数据
            String request = scanner.next();
            if(request.equals("exit")){
                System.out.println("goodbye!");
                return;
            }
            // 2，将数据构造成UDP请求，并发送给客户端
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(),request.getBytes().length,
                    InetAddress.getByName(serverIp),serverPort);
            socket.send(requestPacket);
            // 3，读取服务器的UDP响应，并解析
            DatagramPacket responsePacket = new DatagramPacket(new byte[4096],4096);
            socket.receive(responsePacket);
            String response = new String(responsePacket.getData(),0, responsePacket.getLength());
            // 4，把解析好的结果显示出来
            System.out.println(response);
        }
    }

    public static void main(String[] args) throws IOException {
        UdpEchoClient client = new UdpEchoClient("127.0.0.1",9090);
        client.start();
    }

}
